package com.ikangtai.shecare.stickycalendar.http;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordOptionCopulationButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordOptionSymptomButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectCopulationButton;
import com.ikangtai.shecare.common.baseView.recordButtonView.RecordSelectCopulationContentButton;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncALData;
import com.ikangtai.shecare.common.db.sync.SyncRecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.TemperUploadMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg1;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncRecordInfoMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.record.bean.UserTemperatureInfo;
import com.ikangtai.shecare.stickycalendar.http.util.MensesMsg;
import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by ikangtai on 2016/8/26.
 */
public class RecordHttp {

    private static final OkHttpClient mOkHttpClient = App.getOKHttpClient();
    private Context context;
    private static DBManager dbManager;
    private Algorithm algorithm;

    /* 姨妈来了/走了 相关 */
    private int mensesHintValue = 0;  //显示姨妈来了为1， 显示姨妈走了为0
    private int mensesChoiceValue = 0;  //选择是为1， 选择否为0
    private int referMensesChoiceValue = 0;//初始状态下的选择按钮（1选择开关打开/0关闭）
    public static int mensesBlood; //点击后的状态值（打开姨妈来了、关闭姨妈来了、打开姨妈走了、关闭姨妈走了）
    public static int mensesDysmenorrhea, mensesColor, mensesStatusBlock, mensesStatusOdour, mensesStatusDrossy, mensesFlow; // 痛经、经血颜色、血块、异味、渣状、流量
    private int referMensesBlood;
    public static int mensesInfo;
    private boolean isMensesAlgorithmUsed = false;

    private String lastPeriodDateValue;
    public UserRecordData userRecordData = new UserRecordData();
    public List<UserTemperatureInfo> selectedDayTemper = new ArrayList<UserTemperatureInfo>();
    private List<UserTemperatureInfo> deleteDayTemper = new ArrayList<UserTemperatureInfo>();
    public static int bbtHave, mucusColor, mucusStatus, mucusFlow;

    public static int copulationHaveSex;
    private double referBBT;
    private int referMucusInfo;
    private String copulationSexTime;
    private String memo;
    public static int mucusInfo, viewNum, copulationInfo, symptomTemperInfo;
    public static int viewPosition = 0;
    private String dateRecord;
    private RecordSelectButton recordTemperatureRecordBtn;
    private RecordSelectButton recordTemperatureTimeBtn;
    private EditText memeoEditText;
    RecordSelectCopulationButton recordCopulationYesBtn;
    RecordSelectCopulationButton recordCopulationNoBtn;
    RecordSelectCopulationContentButton recordCopulationTimeBtn;
    RecordOptionCopulationButton recordCopulationContraceptionCondom;
    RecordOptionCopulationButton recordCopulationContraceptionMedicine;
    RecordOptionCopulationButton recordCopulationContraceptionOther;
    RecordOptionCopulationButton recordCopulationPositionKneeChest;
    RecordOptionCopulationButton recordCopulationPositionSupine;
    RecordOptionCopulationButton recordCopulationPositionOther;
    RelativeLayout record_copulation_edit_layout;
    RecordOptionSymptomButton symptomMeasureLateBtn, symptomStayupLateBtn, symptomTripBtn, symptomJetLagBtn, symptomHolidayOutofLifeBtn, symptomWeatherChangeBtn, symptomBigPressureBtn, symptomTooExcitedBtn, symptomDrunkBtn, symptomFeverBtn, symptomSickBtn, symptomNotMensesBleedBtn, symptomDizzyBtn,
            symptomBackAcheBtn, symptomAnxiousBtn, symptomBellyAcheBtn, symptomHeadacheBtn, symptomBreastAcheBtn, symptomBodyAchesBtn;
    private UserRecordData originRecordData = new UserRecordData();
    private List<Double> originDayTempers = new ArrayList<Double>();
    private boolean testPaperIsChanged = false;//判断所有试纸部分是否有改动
    private ProgressDialog progressDialog;
    private boolean isAlgorithmUsed = false;

    private JSONArray jsonArrayCycleDatas, jsonArrayUserDatas;
    private JSONObject jsonObjectUserData;

    public RecordHttp(Context context, List<MensesMsg> mensesMsgList) {

        this.context = context;
        dbManager = new DBManager(context);
        EventBus.getDefault().register(this);
        algorithm = new Algorithm(context);

    }

    private void saveSelectedDayRecord() {
        long currentTime = DateUtil.getStringToDate(DateUtil.getCurrentDay() + " 00:00:00");
        long recordDateZeroTime = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        if (recordDateZeroTime > currentTime) {
            Toast.makeText(context, R.string.edit_record_information_future, Toast.LENGTH_SHORT).show();
            return;
        }
        CycleUnitDS[] cycleUnitDS = dbManager.getAllMensesConfirmStartHaveALCycleOutput(App.userName);
        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0 && cycleUnitDS.length == 1 && cycleUnitDS[0].menstruationStartConfirm == DateUtil.getStringToDate(dateRecord + " 12:00:00")){
            showInputLastPeriodDateDialog();
        }else{
            getRecordInfo();
            if (!isRecordDataChanged()) {
                Toast.makeText(context, R.string.record_information_no_change, Toast.LENGTH_SHORT).show();
                return;
            }

//            showProgressDialog();

//            saveLHAndHCGAndBU();
            syncAndUploadRecordDatas();
        }
    }

    private void showInputLastPeriodDateDialog() {

        Dialog alertDialog = new AlertDialog.Builder(context).
                setTitle(context.getString(R.string.warm_prompt)).
                setMessage(context.getString(R.string.menstruation_another_enter_again)).
                setPositiveButton(context.getString(R.string.sure), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setDateDialog();
                    }
                }).
                create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    private void setDateDialog() {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int year = calendar.get(java.util.Calendar.YEAR);
        int monthofYear = calendar.get(java.util.Calendar.MONTH);
        int dayofMonth = calendar.get(java.util.Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String setLastPeriodDate = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                if (DateUtil.isFutureDate(year + "/" + (monthOfYear + 1) + "/" + dayOfMonth)) {
                    Toast.makeText(context, context.getString(R.string.future_time), Toast.LENGTH_SHORT).show();
                } else {
                    lastPeriodDateValue = setLastPeriodDate;
                    App.memory_preference_lastPeriodDate = setLastPeriodDate;
                    dbManager.updateUserPreference(App.userName, "lastPeriodDate", setLastPeriodDate);
                    userRecordData.setMensesInfo(0);
                    userRecordData.setIsSynced(0);
                    dbManager.saveRecordData(userRecordData);
                    UserRecordData userRecordData1 = dbManager.getSelectedDayRecordData(App.userName, setLastPeriodDate);
                    if (null != userRecordData1.getId() && !"".equals(userRecordData1.getId())) {
                        userRecordData1.setMensesInfo(1);
                        userRecordData1.setIsSynced(0);
                        dbManager.saveRecordData(userRecordData1);
                    } else {
                        userRecordData1.setId(UUID.randomUUID().toString());
                        userRecordData1.setRecordDate(DateUtil.getStringToDate(setLastPeriodDate + " 12:00:00"));
                        userRecordData1.setUserName(App.userName);
                        userRecordData1.setMensesInfo(1);
                        userRecordData1.setIsSynced(0);
                        dbManager.saveRecordData(userRecordData1);
                    }
                    AppLog.e("changeMensesStart is isAlgorithmUsed!");
                    g1Tog2Algorithm();
                    dbManager.initDayUnitDSOutputsList2Memory(App.userName);
                    AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
                    algoUpdateMsg.setRespCode(1);
                    EventBus.getDefault().post(algoUpdateMsg);
                    StatusBarColor(dateRecord);
                    initValue();
                }
            }
        }, year, monthofYear, dayofMonth);
        dialog.setCancelable(false);
        DatePicker datePicker = dialog.getDatePicker();
        datePicker.setMaxDate(new Date().getTime());
        dialog.show();
    }

    private void getRecordInfo() {
        if ("".equals(userRecordData.getId()) || null == userRecordData.getId()) {
            userRecordData.setId(UUID.randomUUID().toString());
        }
        userRecordData.setUserName(App.userName);
        if (selectedDayTemper.size() == 0) bbtHave = 0;
        else bbtHave = 1;
        if (0 == userRecordData.getRecordDate())
            userRecordData.setRecordDate(DateUtil.getStringToDate(dateRecord + " " + recordTemperatureTimeBtn.getText().toString() + ":00"));
        else userRecordData.setRecordEditDate(new Date().getTime() / 1000);
        mucusInfo = (mucusStatus << 1) | (mucusFlow << 4) | (mucusColor << 7);
        AppLog.i("mucusInfo:" + Integer.toBinaryString(mucusInfo));
        userRecordData.setMucusInfo(mucusInfo);

        mensesInfo = (mensesBlood) | (mensesDysmenorrhea << 5) | (mensesFlow << 2) | (mensesColor << 8) | (mensesStatusBlock << 11) | (mensesStatusOdour << 12) | (mensesStatusDrossy << 13);
        AppLog.i("mensesInfo:" + Integer.toBinaryString(mensesInfo));
        userRecordData.setMensesInfo(mensesInfo);

        if (null != memeoEditText.getText())
            userRecordData.setMemoInfo(memeoEditText.getText().toString());
        if (null != recordCopulationTimeBtn.getText() && !context.getResources().getString(R.string.record_copulation_time).equals(recordCopulationTimeBtn.getText().toString())) {
            userRecordData.setSexTime(DateUtil.getStringToDate(dateRecord + " " + recordCopulationTimeBtn.getText().toString() + ":00"));
        }
        copulationInfo = copulationHaveSex | (recordCopulationContraceptionCondom.getBackgroundColor() << 1) | (recordCopulationContraceptionMedicine.getBackgroundColor() << 2) |
                (recordCopulationContraceptionOther.getBackgroundColor() << 3) | (recordCopulationPositionKneeChest.getBackgroundColor() << 7) | (recordCopulationPositionSupine.getBackgroundColor() << 8) |
                (recordCopulationPositionOther.getBackgroundColor() << 9);
        userRecordData.setCopulationInfo(copulationInfo);
        symptomTemperInfo = (bbtHave << 6) | (symptomSickBtn.getBackgroundColor() << 2) | (symptomDrunkBtn.getBackgroundColor() << 3) | (symptomTripBtn.getBackgroundColor() << 4) | (symptomFeverBtn.getBackgroundColor() << 7) |
                (symptomNotMensesBleedBtn.getBackgroundColor() << 8) | (symptomDizzyBtn.getBackgroundColor() << 9) | (symptomBackAcheBtn.getBackgroundColor() << 10) | (symptomAnxiousBtn.getBackgroundColor() << 11) |
                (symptomMeasureLateBtn.getBackgroundColor() << 17) | (symptomStayupLateBtn.getBackgroundColor() << 5) | (symptomJetLagBtn.getBackgroundColor() << 18) | (symptomHolidayOutofLifeBtn.getBackgroundColor() << 19) | (symptomWeatherChangeBtn.getBackgroundColor() << 20) | (symptomBigPressureBtn.getBackgroundColor() << 21) | (symptomTooExcitedBtn.getBackgroundColor() << 22) |
                (symptomBellyAcheBtn.getBackgroundColor() << 12) | (symptomHeadacheBtn.getBackgroundColor() << 13) | (symptomBreastAcheBtn.getBackgroundColor() << 14) | (symptomBodyAchesBtn.getBackgroundColor() << 16);
        userRecordData.setSymptomInfo(symptomTemperInfo);
    }

    private boolean isRecordDataChanged() {
        boolean result = false;
        boolean baseRecordInfoChanged = checkBaseRecordInfoChanged();
        boolean temperChanged = checkTemperInfoChanged();
        //检查信息是否修改
        result = baseRecordInfoChanged || temperChanged || testPaperIsChanged;
        return result;
    }

    private boolean checkBaseRecordInfoChanged() {
        boolean result = false;
        if (originRecordData.getMensesInfo() != userRecordData.getMensesInfo()) return true;
        if (originRecordData.getSexTime() != userRecordData.getSexTime()) return true;
        if (originRecordData.getCopulationInfo() != userRecordData.getCopulationInfo()) return true;
        if (originRecordData.getMucusInfo() != userRecordData.getMucusInfo()) return true;
        int originSymptom = originRecordData.getSymptomInfo();
        if (0 != divideBytes(originRecordData.getSymptomInfo(), 1, 6)) {
            originSymptom -= 64;
        }
        int userSymptom = userRecordData.getSymptomInfo();
        if (0 != divideBytes(userRecordData.getSymptomInfo(), 1, 6)) {
            userSymptom -= 64;
        }
        if (originSymptom != userSymptom) return true;
        if (null != originRecordData.getMemoInfo() && null != userRecordData.getMemoInfo()) {
            if (!originRecordData.getMemoInfo().equals(userRecordData.getMemoInfo())) return true;
        } else {
            if (null != originRecordData.getMemoInfo() && !"".equals(originRecordData.getMemoInfo()) && null == userRecordData.getMemoInfo())
                return true;
            if (null == originRecordData.getMemoInfo() && null != userRecordData.getMemoInfo() && !"".equals(userRecordData.getMemoInfo()))
                return true;
        }
        return result;
    }

    private int divideBytes(int value, int bits, int position) {

        return (value >> position) & (int) (Math.pow(2, bits) - 1);
    }

    private boolean checkTemperInfoChanged() {
        boolean result = false;
        AppLog.e("originDayTempers.size():" + originDayTempers.size() + "selectedDayTemper.size():" + selectedDayTemper.size());
        if (originDayTempers.size() != selectedDayTemper.size()) return true;
        if (originDayTempers.size() > 0) {
            for (int i = 0; i < originDayTempers.size(); i++) {
                if (originDayTempers.get(i) != selectedDayTemper.get(i).getTemperature()) {
                    return true;
                }
            }
        } else return false;
        return result;
    }

    private void showProgressDialog() {
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(context.getString(R.string.saving));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void syncAndUploadRecordDatas() {
        if (InternetUtil.hasInternet()) {
            SyncRecordInfoMsg syncRecordInfoMsg = new SyncRecordInfoMsg();
            syncRecordInfoMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);
            SyncRecordInfo syncRecordInfo = new SyncRecordInfo(context, syncRecordInfoMsg);
            AppLog.e("SyncRecordInfoWithNetwork");
            syncRecordInfo.syncRecordInfoWithNetwork();
        } else {
            uploadRecordInfo();
        }
    }

    private void uploadRecordInfo() {

        getRecordInfo();
//        if (selectedDayTemper.size() > 0 || deleteDayTemper.size() > 0) { // 给userRecordData中封装体温数据
//            UserTemperatureInfo[] userTemperatureInfos = new UserTemperatureInfo[selectedDayTemper.size() + deleteDayTemper.size()];
//            if (selectedDayTemper.size() > 0) {
//                for (int i = 0; i < selectedDayTemper.size(); i++) {
//                    userTemperatureInfos[i] = selectedDayTemper.get(i);
//                }
//                if (deleteDayTemper.size() > 0) {
//                    for (int i = selectedDayTemper.size(); i < (selectedDayTemper.size() + deleteDayTemper.size()); i++) {
//                        userTemperatureInfos[i] = deleteDayTemper.get(i - selectedDayTemper.size());
//                    }
//                }
//                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
//
//            } else {
//                for (int i = 0; i < deleteDayTemper.size(); i++) {
//                    userTemperatureInfos[i] = deleteDayTemper.get(i);
//                }
//
//                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
//            }
//        }

        JSONArray jsonArray = new JSONArray();
        jsonArray.put(userRecordData.getUserRecordDataInfoJson());
        AppLog.i("authToken = " + App.authToken + ", jsonArray = " + jsonArray.toString());
        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        String appendUrl = "sync/addSignsRecords.json";
        try {

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("records", jsonArray);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveRecordData(0);
//                    saveTemperatureRecord(0);
                    syncAndUpdateCycleDatas(0);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String str = response.body().string();
                        AppLog.i("addSignsRecords response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("addSignsRecords onResponse success!");
                            saveRecordData(1);
//                            saveTemperatureRecord(1);
                            syncAndUpdateCycleDatas(1);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                            temperUploadMsg.setUpdateCode(App.HTTP_RESP_TOKEN_TIME_OUT);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else {
                            AppLog.i("addSignsRecords onResponse failed! respCode = " + respCode);
                            saveRecordData(0);
//                            saveTemperatureRecord(0);
                            syncAndUpdateCycleDatas(0);
                        }
                    } catch (JSONException e) {
                        saveRecordData(0);
//                        saveTemperatureRecord(0);
                        syncAndUpdateCycleDatas(0);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            saveRecordData(0);
//            saveTemperatureRecord(0);
            syncAndUpdateCycleDatas(0);
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
        }
    }

    private void saveRecordData(int isSynced) {
        userRecordData.setIsSynced(isSynced);
        dbManager.saveRecordData(userRecordData);

//        if (userRecordData.getMensesInfo() == 0 && originRecordData.getMensesInfo() != 0) {
//            if (null != dbManager.getLastMensesRecordData(App.userName)) {
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
//            }
//        } else if (userRecordData.getMensesInfo() != 0) {
//            if (null != dbManager.getLastMensesRecordData(App.userName)) {
//                App.memory_preference_lastPeriodDate = DateUtil.getDateStr2bit(dbManager.getLastMensesRecordData(App.userName).getRecordDate());
//                dbManager.updateUserPreference(App.userName, "lastPeriodDate", App.memory_preference_lastPeriodDate);
//            }
//        }

    }

    private void saveTemperatureRecord(int isSynced) {

        if (selectedDayTemper.size() > 0) {
            for (int i = 0; i < selectedDayTemper.size(); i++) {
                selectedDayTemper.get(i).setSyncType(isSynced);
                dbManager.saveTempearatureData(selectedDayTemper.get(i));
            }
        }
        if (deleteDayTemper.size() > 0) {
            for (int i = 0; i < deleteDayTemper.size(); i++) {
                deleteDayTemper.get(i).setSyncType(isSynced);
                dbManager.saveTempearatureData(deleteDayTemper.get(i));
            }
        }
    }

    private void syncAndUpdateCycleDatas(int isSynced) {
        if (InternetUtil.hasInternet()) {
            SyncALDataMsg syncALDataMsg = new SyncALDataMsg();
            syncALDataMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT);

            SyncALData syncALData = new SyncALData(context, syncALDataMsg);
            AppLog.e("SyncALDataWithNetwork");
            syncALData.SyncALDataWithNetwork();
        } else {
            updateCycleDatas(isSynced);
        }
    }

    /**
     * 姨妈来了调用的算法
     *
     *wzz 算法
     *
     * @param isSynced
     */
    private void updateCycleDatas(int isSynced) {
        long recordDaySeconds = DateUtil.getStringToDate(dateRecord + " 00:00:00");
        AppLog.e("start algorithm in recordFragment");
        if(mensesHintValue == 1 && referMensesChoiceValue == 0 && mensesBlood == 1){//1姨妈来了/0走了   初始状态下的选择按钮（1选择开关打开/0关闭）      点击后的状态值
            AppLog.i("algorithm Menses inputStart");
            int result = algorithm.executeAL(2, algorithm.getMensesDayInput(recordDaySeconds, 2), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            isAlgorithmUsed = true;
            isMensesAlgorithmUsed = true;
        }
        if(mensesHintValue == 0 && referMensesChoiceValue == 0 && mensesBlood == 1){
            AppLog.i("algorithm Menses inputEnd");
            int result = algorithm.executeAL(3, algorithm.getMensesDayInput(recordDaySeconds, 3), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            isAlgorithmUsed = true;
            isMensesAlgorithmUsed = true;
        }
        if(mensesHintValue == 1 && referMensesChoiceValue == 1 && mensesBlood == 0){
            AppLog.i("algorithm Menses deleteStart");
            int result = algorithm.executeAL(4, algorithm.getMensesDayInput(recordDaySeconds, 4), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);
            AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
            long periodAchieveConfirm = dbManager.getSelectedDayALDayUnitDSOutput(App.userName, currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm;
            AppLog.e("periodAchieveConfirm:" + periodAchieveConfirm);
            if(periodAchieveConfirm == 0){
                changeForecastStart();
            }
            isAlgorithmUsed = true;
            isMensesAlgorithmUsed = true;
        }
        if(mensesHintValue == 0 && referMensesChoiceValue == 1 && mensesBlood == 0){
            AppLog.i("algorithm Menses deleteEnd");
            int result = algorithm.executeAL(5, algorithm.getMensesDayInput(recordDaySeconds, 5), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), isSynced);
            if(result == 234) g1Tog2Algorithm();
            isAlgorithmUsed = true;
            isMensesAlgorithmUsed = true;
        }

//        /**
//         * 温度算法有关
//         */
//        long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime()/1000);//（取今天的时间）当前周期的经期开始时间
//        AppLog.e("currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);
//        long firstMensesStartConfirm = dbManager.getCycleUnitDSMensesFirstStartConfirm(App.userName);//整个算法数据中的第一个经期开始时间
//        AppLog.e("firstMensesStartConfirm:" + firstMensesStartConfirm);
//        if(currentDayCycleUnitDSMensesStartConfirm < recordDaySeconds ){
//            if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
//                AppLog.i("algorithm bbt");
//                int result = algorithm.executeAL(11, algorithm.getBBTDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//                if(result == 234) g1Tog2Algorithm();
//                referBBT = selectedDayTemper.get(0).getTemperature();
//                isAlgorithmUsed = true;
//            }
//        }else{
//            if((firstMensesStartConfirm > 0 && recordDaySeconds >firstMensesStartConfirm)){
//
//            }if ((selectedDayTemper.size() > 0) && (referBBT != selectedDayTemper.get(0).getTemperature())) {
//                AppLog.i("algorithm bbt history");
//                int result = algorithm.executeAL(23, algorithm.getHistoryBBTDayInput(recordDaySeconds), algorithm.getHistoryBBTCycleInput(recordDaySeconds), isSynced);
//                if(result == 234) g1Tog2Algorithm();
//                referBBT = selectedDayTemper.get(0).getTemperature();
//                isAlgorithmUsed = true;
//            }
//        }
//
//        /**
//         * 宫颈粘液算法相关
//         */
//        if (mucusInfo != 0 && mucusInfo != referMucusInfo) {
//            AppLog.i("algorithm mucus");
//            int result = algorithm.executeAL(12, algorithm.getMucusDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
//            if(result == 234) g1Tog2Algorithm();
//            referMucusInfo = mucusInfo;
//            isAlgorithmUsed = true;
//        }

        /**
         * 调用算法后更新UI
         */
        if (isAlgorithmUsed) {
            isAlgorithmUsed = false;
            jsonArrayCycleDatas = algorithm.getCycleOutputJson();
            jsonArrayUserDatas = algorithm.getDayOutputJson();
            jsonObjectUserData = algorithm.getUserInfoJson();
            dbManager.initDayUnitDSOutputsList2Memory(App.userName);
            AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
            algoUpdateMsg.setRespCode(1);
            EventBus.getDefault().post(algoUpdateMsg);
            if (isSynced == 1)
                uploadCycleDatas();
            else {
                AppLog.e("msg at is not synced!");
                TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                temperUploadMsg.setUpdateCode(2);
                EventBus.getDefault().post(temperUploadMsg);
            }
        } else {
            AppLog.e("msg at is not isAlgorithmUsed!");
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);
        }
    }

    //算法返回值为234时调用一代转二代
    private void g1Tog2Algorithm(){
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = App.memory_preference_mensesLen;
        userData.averageCycleLength = App.memory_preference_periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);
        algorithm.g1FirstLoginG2(userData, dayInput, 0);
        checkIfNeedDealHistoryData();
    }

    private void checkIfNeedDealHistoryData() {
        CycleUnitDS[] cycleUnitDSes = dbManager.getALCycleOutput(App.userName, null);
        if(null != cycleUnitDSes && cycleUnitDSes.length > 0){
            for(int i = 0; i < cycleUnitDSes.length; i++){
                cycleUnitDSes[i].ovulationDayUserRecordBasis = -99;
            }
            dbManager.saveALCycleOutput(cycleUnitDSes, 0);
        }

        List<DayUnitDSOutput> dayUnitDSOutputs = dbManager.getALDayUnitDSOutputList(App.userName);
        if(null != dayUnitDSOutputs && dayUnitDSOutputs.size() > 0){
            for(int i = 0; i < dayUnitDSOutputs.size(); i++){
                dayUnitDSOutputs.get(i).periodAchieveForecast = 99;
            }
            dbManager.saveALDayOutput(dayUnitDSOutputs, 0);
        }
        saveALResult2Sqlite(0);
    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }

    private void changeForecastStart() {
        long zeroTime = DateUtil.getDateZeroTime2bit(new Date().getTime() / 1000) - 12 * 3600;
        int result = algorithm.executeAL(7, algorithm.getChangeForecastMensesStartDayInput(zeroTime), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), 0);
        if(result == 234) g1Tog2Algorithm();
    }

    private void uploadCycleDatas() {

        OKHttpUtil okHttpClient = new OKHttpUtil(context);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas);
            AppLog.i("userData = " + jsonArrayUserDatas);
            AppLog.i("userInfo = " + jsonObjectUserData);
            okHttpClient.add("authToken", App.authToken);
            AppLog.i("authToken = " + App.authToken);
            if (null != jsonArrayCycleDatas)
                okHttpClient.add("cycleData", jsonArrayCycleDatas);
            if (null != jsonArrayUserDatas)
                okHttpClient.add("userData", jsonArrayUserDatas);
            if (null != jsonObjectUserData)
                okHttpClient.add("userInfo", jsonObjectUserData);
            if (null == jsonArrayCycleDatas && null == jsonObjectUserData && null == jsonArrayUserDatas)
                return;
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    algorithm.saveALData2Sqlite(0);
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    temperUploadMsg.setUpdateCode(2);
                    EventBus.getDefault().post(temperUploadMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            AppLog.i("UploadCycleData onResponse success!");
                            temperUploadMsg.setUpdateCode(2);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadCycleDatas();
                        } else {
                            algorithm.saveALData2Sqlite(0);
                            temperUploadMsg.setUpdateCode(2);
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            EventBus.getDefault().post(temperUploadMsg);
                        }
                    } catch (JSONException e) {
                        algorithm.saveALData2Sqlite(0);
                        e.printStackTrace();
                        temperUploadMsg.setUpdateCode(2);
                        EventBus.getDefault().post(temperUploadMsg);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            algorithm.saveALData2Sqlite(0);
            e.printStackTrace();
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(2);
            EventBus.getDefault().post(temperUploadMsg);

        }
    }

    private void StatusBarColor(String dateRecord) {
        long dateCurrent = DateUtil.getStringToDate(dateRecord + " 12:00:00");
        int i = -1;
        for (int n = 0; n < App.dayUnitDSOutputsList.size(); n++) {
            if (dateCurrent == App.dayUnitDSOutputsList.get(n).date) {
                i = n;
                break;
            }
        }
//        topBar.setBackgroundResource(getBGcolor(i));
//        StatusBarUtil.setColor(getActivity(), getResources().getColor(getBGcolor(i)), 0);
    }

    private void initValue() {
        mensesInfo = 0;
        mucusInfo = 0;
        mucusColor = 0;
        mucusStatus = 0;
        mucusFlow = 0;
        mensesBlood = 0;
        mensesDysmenorrhea = 0;
        mensesColor = 0;
        mensesStatusBlock = 0;
        mensesStatusOdour = 0;
        mensesStatusDrossy = 0;
        mensesFlow = 0;
        memo = null;
        copulationSexTime = null;
        copulationHaveSex = 0;
        symptomTemperInfo = 0;
        copulationInfo = 0;
        referBBT = 0.0;
        referMensesBlood = 0;
        referMucusInfo = 0;
        recordTemperatureRecordBtn.setText(context.getResources().getString(R.string.record_bbt_temperature));

//        clearMucusView();
//        clearMensesView();
//        clearCopulationView();
//        clearSymptomView();
//        hideBBTEditView();
        memeoEditText.setText(null);
        userRecordData = dbManager.getSelectedDayRecordData(App.userName, dateRecord);
        originRecordData.setMensesInfo(userRecordData.getMensesInfo());
        originRecordData.setMucusInfo(userRecordData.getMucusInfo());
        originRecordData.setCopulationInfo(userRecordData.getCopulationInfo());
        originRecordData.setMemoInfo(userRecordData.getMemoInfo());
        originRecordData.setSexTime(userRecordData.getSexTime());
        originRecordData.setSymptomInfo(userRecordData.getSymptomInfo());
        AppLog.i(userRecordData.getId());
        if (null != userRecordData.getId() && !"".equals(userRecordData.getId())) {
            mucusInfo = userRecordData.getMucusInfo();
            referMucusInfo = mucusInfo;
            AppLog.i("mucus info:" + mucusInfo);
//            initMucusValue(mucusInfo);
            mensesInfo = userRecordData.getMensesInfo();
//            initMensesValue(mensesInfo);
            copulationInfo = userRecordData.getCopulationInfo();
//            initCopulationValue();
            symptomTemperInfo = userRecordData.getSymptomInfo();
//            initSymptomValue();
            if (0 != userRecordData.getSexTime()) {
                copulationSexTime = DateUtil.getTimeStr(userRecordData.getSexTime());
                recordCopulationTimeBtn.setText(copulationSexTime);
            }
            memo = userRecordData.getMemoInfo();
            if (null != memo) memeoEditText.setText(memo);
        }
        selectedDayTemper.clear();
        deleteDayTemper.clear();
        originDayTempers.clear();
        selectedDayTemper = dbManager.getSelectedDayTemperature(App.userName, dateRecord);
        AppLog.i("selectedDayTemper:" + selectedDayTemper.size());
        if (selectedDayTemper.size() != 0) {
            selectedDayTemper.get(0).setIsBBT(1);
//            sortSelectedTemper();
            referBBT = selectedDayTemper.get(0).getTemperature();
            for (int i = 0; i < selectedDayTemper.size(); i++) {
                originDayTempers.add(selectedDayTemper.get(i).getTemperature());
            }
        }
//        updateTemperatureShowView();
//        setCurrentRecordMensesType();
        mensesInfo = (mensesBlood) | (mensesDysmenorrhea << 5) | (mensesFlow << 2) | (mensesColor << 8) | (mensesStatusBlock << 11) | (mensesStatusOdour << 12) | (mensesStatusDrossy << 13);
        originRecordData.setMensesInfo(mensesInfo);
        referMensesBlood = mensesBlood;
    }

    @Subcriber
    private void syncRecordDataInRecordActivity(SyncRecordInfoMsg syncRecordInfoMsg) {
        if (syncRecordInfoMsg.getSyncInActivity().equals(SyncRecordInfoMsg.SYNC_RECORD_IN_RECORDFRAGMENT)) {
            uploadRecordInfo();
        }
    }

    @Subcriber
    private void syncRecordChangeALData(SyncALDataMsg1 syncALDataMsg) {
        if (syncALDataMsg.getSyncInActivity().equals(SyncALDataMsg.SYNC_IN_RECORDFRAGMENT)) {
            if (algorithm != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        updateCycleDatas(1);
                    }
                }).start();
            }
        }
    }

}
